package com.monkey_pig.memoryalbum.activity;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;

import com.monkey_pig.memoryalbum.R;
import com.monkey_pig.memoryalbum.activity.adapter.GridImageAdapter;
import com.monkey_pig.memoryalbum.activity.entity.ChildEntity;
import com.monkey_pig.memoryalbum.common.AppContext;
import com.monkey_pig.memoryalbum.utils.BitmapUtils;
import com.monkey_pig.memoryalbum.utils.L;
import com.monkey_pig.memoryalbum.utils.MyUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link MyFootFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link MyFootFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MyFootFragment extends Fragment {

    //Activity中通过查询MediaStore的多媒体图片库来查询所有的图片的缩略图，缩略图所在的位置是：MediaStore.Images.Thumbnails
    //缩略图 id
    private int[] thumbIds;
    private Cursor cursor;

    private GridImageAdapter imageAdapter;

    @Bind(R.id.gview_image)
    GridView gviewImage;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_my_foot, container, false);
        ButterKnife.bind(this, view);
        gviewImage.setOnItemClickListener(photoClickListener);
        showThumbnails();
        return view;
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }





    private void showThumbnails(){

        cursor = BitmapUtils.queryThumbnails(getActivity());
        //日期列表
        List<String> Fdtimes = new ArrayList<String>();
        if(cursor.moveToFirst()){
            List<ChildEntity> bitmaps = new ArrayList<ChildEntity>();
            thumbIds = new int[cursor.getCount()];
            for(int i=0; i<cursor.getCount();i++){
                cursor.moveToPosition(i);
                String currPath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails.DATA));
                thumbIds[i] = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID));
                //通过缩略图id获取原图路径，然后获取到拍摄日期
                L.d("全部日期：",MyUtils.getFDateTime(BitmapUtils.queryImagePathByThumbnailId(getActivity(), thumbIds[i])));
                Fdtimes.add(MyUtils.fomartString(MyUtils.getFDateTime(BitmapUtils.queryImagePathByThumbnailId(getActivity(), thumbIds[i]))));
                Bitmap b = BitmapUtils.decodeBitmap(currPath,100,100);
                ChildEntity tempItem = new ChildEntity(b);
                bitmaps.add(tempItem);
            }

            List<HashMap<String, List<Integer>>> mounths_to_ids=test(Fdtimes, thumbIds);
            L.d("处理后的日期：",mounths_to_ids.toString());
            imageAdapter = new GridImageAdapter(AppContext.getContext(), bitmaps);
            gviewImage.setAdapter(imageAdapter);
        }
    }

    private AdapterView.OnItemClickListener photoClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> p, View v, int position,
                                long id) {
            //点击某张缩略图时，转到图片显示界面
            Intent intent = new Intent();
            intent.setClass(AppContext.getContext(), GalleryActivity.class);
            intent.putExtra("thumbIds", thumbIds);
            intent.putExtra("currentPos", position);
            startActivity(intent);
        }
    };

    private List<HashMap<String, List<Integer>>> test(List<String> fdtimes, int[] thumbIds) {
        L.d("处理前的日期：",fdtimes.toString());
        L.d("相等吗？",fdtimes.size()==thumbIds.length?"是的":"不是");
//        单独时间（月）对应的缩略图id
        List<HashMap<String, List<Integer>>> mounths_to_ids = new ArrayList<HashMap<String, List<Integer>>>();
        //时间去重
        List<String> listWithoutDup = new ArrayList<String>(new HashSet<String>(fdtimes));
        for (int i = 0; i < listWithoutDup.size(); i++) {
            List<Integer> thumbId_item = new ArrayList<>();
            for (int j = 0; j < fdtimes.size(); j++) {
                if (listWithoutDup.get(i) == fdtimes.get(j)) {
                    thumbId_item.add(thumbIds[j]);
                    L.d("处理前的id：", String.valueOf(thumbIds[j]));

                }
            }
            //单月对应ids
            HashMap<String, List<Integer>> map = new HashMap<>();
            map.put(listWithoutDup.get(i), thumbId_item);
            //链接成完整对象
            mounths_to_ids.add(map);
        }
        return mounths_to_ids;
    }

}
